global outcomes      aminwage wrcon sosec   empquality_ind

* Create a file to store results
capture file close medresults
file open medresults using "$results\01_tables\Table_S20_mediation_results.tex", write replace

* Start LaTeX document
file write medresults "\documentclass{article}" _n
file write medresults "\usepackage{booktabs}" _n
file write medresults "\usepackage{caption}" _n
file write medresults "\begin{document}" _n

foreach o of global outcomes {
    file write medresults "\section*{`o'}" _n
    file write medresults "\emph{Note: Knowledge = 0 if no knowledge, Knowledge = 1 if Knowledge is moderate or high}" _n
    file write medresults "\begin{table}[htbp]" _n
    file write medresults "\begin{tabular}{lccccc}" _n
    file write medresults "\toprule" _n
    file write medresults "Wave & Statistic & Coefficient & Rob. Std. Err. & P-value & N \\" _n
    file write medresults "\midrule" _n
    
    foreach x of numlist 1/3 {
        use "$data\4_individual_ano_reg_`x'.dta", clear
        merge m:1 id wave using "$data\2_firm_regressions_individual_paper.dta", keepusing(knowledge_baseline knowledge_2)  
        keep if _merge == 3
        
        gen knowledge = .
        replace knowledge = 0 if knowledge_2 == 1 
        replace knowledge = 1 if knowledge_2 == 3 | knowledge_2 == 2 
        bys id: egen knowledge_max = max(knowledge)
		
		gen increased_knowledge = (knowledge_2 > knowledge_baseline)
		replace increased_knowledge = 1 if knowledge_2==3 & knowledge_baseline==3

		gen change_knowledge = knowledge_2 - knowledge_baseline
		replace increased_knowledge = . if change_knowledge<0
        * Run mediation
        mediate (`o' `o'_2021 missing_`o'_2021 $controls_balance i.strata_all_coll i.wave) (knowledge_max) (assignment), vce(cl id) 
        
        matrix results = r(table)
        local N = e(N)
        
        * Format numbers
        local coef1 : display %5.3f results[1,1]
        local se1 : display %5.3f results[2,1]
        local p1 : display %5.3f results[4,1]
        
        local coef2 : display %5.3f results[1,2]
        local se2 : display %5.3f results[2,2]
        local p2 : display %5.3f results[4,2]
        
        local coef3 : display %5.3f results[1,3]
        local se3 : display %5.3f results[2,3]
        local p3 : display %5.3f results[4,3]
        
        * Write results
        file write medresults "`x' & Indirect Effect & `coef1' & `se1' & `p1' & `N' \\" _n
        file write medresults "`x' & Direct Effect & `coef2' & `se2' & `p2' & `N' \\" _n
        file write medresults "`x' & Total Effect & `coef3' & `se3' & `p3' & `N' \\" _n
        if `x' < 3 {
            file write medresults "\midrule" _n
        }
    }
}

    file write medresults "\bottomrule" _n
    file write medresults "\end{tabular}" _n
    file write medresults "\end{table}" _n
 